﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using Xwang.Task.Model;

namespace Xwang.Task.WebUI.Controllers
{
    /// <summary>
    /// 任务的增删改处理
    /// </summary>
    public class TaskController : AppController
    {
        //
        // GET: /Task/

        IBll.ITaskInfoService TaskInfoService { get; set; }

        IBll.ITaskFeedbackService TaskFeedbackService { get; set; }

        IBll.IUserInfoService UserInfoService { get; set; }

        IBll.ITaskJoinUserService TaskJoinUserService { get; set; }

        /// <summary>
        /// 新建任务，右上角按钮
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public ActionResult Add(TaskInfo task)
        {
            try
            {
                task.Biller = LoginUserInfo.KeyId;
                task.BillDate = DateTime.Now;
                task.TaskDesc = "";
                TaskInfoService.Add(task);
                var count = TaskInfoService.Savechanges();
                return Json(new
                {
                    success = count > 0,
                    msg = count > 0 ? "ok" : "新增任务失败！",
                    data = new[]{
                        new
                        {
                            task.KeyId,
                            task.TaskTitle,
                            UserName = LoginUserInfo.UserName.Substring(0, 1).ToUpper(),
                            endtime = task.TaskEndTime == null ? "" : task.TaskEndTime.Value.ToString("yy-MM-dd"),
                            over = task.TaskEndTime == null ? 0 : task.TaskEndTime.Value.AddDays(1).CompareTo(DateTime.Now)
                        }
                    }
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message

                }, JsonRequestBehavior.AllowGet);
            }
        }


        /// <summary>
        /// 获取任务列表，按任务分类获取
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult GetListByKind(int type)
        {
            var list = TaskInfoService.LoadEntities(t => t.TaskListKind == type && t.TaskStatus != 3);
            return Json(new
            {
                success = true,
                msg = "ok",
                data = from task in list
                       select new
                       {
                           task.KeyId,
                           task.TaskTitle,
                           UserName = task.UserInfo.UserName,
                           endtime = task.TaskEndTime == null ? "" : task.TaskEndTime.Value.ToString("yy-MM-dd"),
                           over = task.TaskEndTime == null ? 0 : task.TaskEndTime.Value.AddDays(1).CompareTo(DateTime.Now)
                       }
            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 根据任务ID，获取任务详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetTask(int id)
        {
            var task = TaskInfoService.LoadEntities(t => t.KeyId == id).FirstOrDefault();

            return Json(new
            {
                success = true,
                msg = "ok",
                data = new
                {
                    task.KeyId,
                    task.TaskListKind,
                    task.TaskTitle,
                    task.TaskDesc,
                    users = from user in task.TaskJoinUser
                            select new
                            {
                                user.UserInfo.UserName,
                                user.UserId,
                                av = user.UserInfo.UserName.Substring(0, 1)
                            },
                    feedback =
                        from feed in task.TaskFeedback.Where(t => t.FType == 3)
                        select new
                        {
                            feed.UserInfo.UserName,
                            feed.FContent,
                            time = feed.FeedbackTime.ToString("MM-dd HH:mm:ss")
                        }
                }
            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 更新任务的标题及详细描述信息
        /// </summary>
        /// <param name="taskInfo"></param>
        /// <returns></returns>
        public ActionResult Update(TaskInfo taskInfo)
        {
            try
            {
                var task = TaskInfoService.LoadEntities(t => t.KeyId == taskInfo.KeyId).FirstOrDefault();
                task.TaskTitle = taskInfo.TaskTitle;
                task.TaskDesc = taskInfo.TaskDesc;
                var count = TaskInfoService.Savechanges();
                return Json(new
                {
                    success = count > 0,
                    msg = count > 0 ? "ok" : "更新任务失败！"
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        ///  发布评论信息
        /// </summary>
        /// <returns></returns>
        public ActionResult AddFeedBack(TaskFeedback feedback)
        {
            try
            {
                feedback.FeedbackTime = DateTime.Now;
                feedback.FType = 3;
                feedback.UserId = LoginUserInfo.KeyId;
                TaskFeedbackService.Add(feedback);
                var count = TaskFeedbackService.Savechanges();
                return Json(new
                {
                    success = count > 0,
                    msg = count > 0 ? "ok" : "发布评论失败！",
                    feedback =
                      new[]{
                        new
                        {
                            LoginUserInfo.UserName,
                            feedback.FContent,
                            time = feedback.FeedbackTime.ToString("MM-dd HH:mm:ss")
                        }
                     }
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message

                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取不在任务中的用户列表
        /// </summary>
        /// <param name="taskid"></param>
        /// <returns></returns>
        public ActionResult GetUserNotInTask(int taskid, string username = "")
        {
            try
            {
                var uids = from task in TaskJoinUserService.LoadEntities(u => u.TaskId == taskid)
                           select task.UserId;

                var users = UserInfoService.LoadEntities(u => !uids.Contains(u.KeyId) && u.UserName.Contains(username));
                return Json(new
                {
                    success = true,
                    msg = "ok",
                    users = from user in users
                            select new
                            {
                                user.UserName,
                                UserId = user.KeyId,
                                av = user.UserName.Substring(0, 1)
                            }
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message

                }, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult AddJoinUser(TaskJoinUser tjUser)
        {
            try
            {

                var count1 =
                    TaskJoinUserService.LoadEntities(t => t.UserId == tjUser.UserId && t.TaskId == tjUser.TaskId)
                        .Count();
                if (count1 > 0)
                {
                    return Json(new
                    {
                        success = false,
                        msg = "无需重复分配"
                    }, JsonRequestBehavior.AllowGet);
                }

                tjUser.Status = 0;
                TaskJoinUserService.Add(tjUser);
                var count = TaskJoinUserService.Savechanges();
                return Json(new
                {
                    success = count > 0,
                    msg = count > 0 ? "ok" : "分配任务失败！"
                }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message

                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 按人员区任务列表
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public ActionResult GetTasksByUser(string start, string end, int userid = 0)
        {
            try
            {
                DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
                long lTime = long.Parse(start + "0000000");
                TimeSpan toNow = new TimeSpan(lTime);
                var ltime2 = long.Parse(end + "0000000");
                var tonow2 = new TimeSpan(ltime2);

                var t1 = dtStart.Add(toNow);
                var t2 = dtStart.Add(tonow2);

                if (userid == 0)
                {
                    userid = LoginUserInfo.KeyId;
                }
                var tasks = TaskJoinUserService.LoadEntities(tj =>
                   (tj.UserId == userid || tj.Task.Biller == userid)
                    && tj.Task.TaskBeginTime >= t1
                    );
                return Json(new
                {
                    success = true,
                    msg = "ok",
                    data = from t in tasks
                           select new
                           {
                               id = t.TaskId,
                               title = t.Task.TaskTitle,
                               start = t.Task.BillDate.ToString("yyyy-MM-dd"),
                               endtime = t.Task.TaskEndTime.HasValue ? t.Task.TaskEndTime.Value.ToString("yyyy-MM-dd") : ""
                           }

                }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message

                }, JsonRequestBehavior.AllowGet);
            }
        }


        /// <summary>
        /// 按部门取任务列表
        /// </summary>
        /// <param name="depid"></param>
        /// <returns></returns>
        public ActionResult GetTasksByDep(int depid)
        {
            try
            {
                var tasks = TaskJoinUserService.LoadEntities(tj => tj.UserInfo.DepId == depid || tj.Task.UserInfo.DepId == depid);
                return Json(new
                {
                    success = true,
                    msg = "ok",
                    data = from t in tasks
                           select new
                           {
                               id = t.TaskId,
                               title = t.Task.TaskTitle,
                               start = t.Task.BillDate.ToString("yyyy-MM-dd"),
                               endtime = t.Task.TaskEndTime.HasValue ? t.Task.TaskEndTime.Value.ToString("yyyy-MM-dd") : ""
                           }

                }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message

                }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
